import { Module } from 'vuex';

import router from '@/router';

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login';

import type { IRootState } from '../types';
import { ILoginState } from './types';

import localCache from '@/utils/cache';
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/map.menus';

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: [],
      userMenus: [],
      permissions: []
    };
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;

      // 动态加载的路由。。
      const routes = mapMenusToRoutes(userMenus);
      routes.forEach((route) => {
        router.addRoute('main', route);
      });

      // 获取用户权限相关内容
      state.permissions = mapMenusToPermissions(userMenus);
    }
  },
  actions: {
    // 账号登录逻辑
    async accountLoginAction({ commit, dispatch }, payload: any) {
      // 1.执行登录
      const loginUserDate = await accountLoginRequest(payload);
      const { id, token } = loginUserDate.data;
      commit('changeToken', token);
      localCache.setCache('token', token);

      // 发送初始化的请求, 在合理放松就不会出现没有token的bug
      dispatch('getInitialDataAction', null, { root: true });

      // 2.获取登录用户信息
      const requestUserInfo = await requestUserInfoById(id);
      const userInfo = requestUserInfo.data;
      commit('changeUserInfo', userInfo);
      localCache.setCache('userInfo', userInfo);
      // 3.获取登录用户菜单列表
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id);
      const userMenus = userMenusResult.data;
      commit('changeUserMenus', userMenus);
      localCache.setCache('userMenus', userMenus);
      // 4.跳转到首页
      router.push('/main');
    },
    // phoneLoginAction({ commit }, payload: any) {
    //   console.log('执行了phoneLoginAction', payload);
    // },

    // 初始化login State 数据，前面保存到了本地
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token');
      if (token) {
        commit('changeToken', token);
        // 发送初始化的请求, 在合理放松就不会出现没有token的bug
        dispatch('getInitialDataAction', null, { root: true });
      }

      const userInfo = localCache.getCache('userInfo');
      if (userInfo) commit('changeUserInfo', userInfo);

      const userMenus = localCache.getCache('userMenus');
      if (userMenus) commit('changeUserMenus', userMenus);
    }
  }
};

export default loginModule;
